package tzy.imageloader;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.util.LruCache;
import android.widget.ImageView;

import java.lang.ref.WeakReference;


/**
 * Created by Administrator on 2017/6/27 0027.
 */

public abstract class BaseImageLoader implements ImageLoader {
    private final LruCache<String, Bitmap> mMemoryCache;

    public BaseImageLoader() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount() / 1024;
            }
        };
    }

    private static final String TAG = "BaseImageLoader";

    @Override
    public void loadImage(ImageView imageView, String resource, Bitmap empty) {
        if (cancelWork(resource, imageView)) {
            final Bitmap bitmap = getBitmapFromMemCache(resource);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            } else {
                final BitmapTask task = new BitmapTask(imageView);
                AsyncDrawable drawable = new AsyncDrawable(imageView.getContext().getResources(), empty, task);
                imageView.setImageDrawable(drawable);
                task.execute(resource);
            }
        }
    }

    @Override
    public void loadImage(ImageView imageview, String resource) {
        loadImage(imageview, resource, null);
    }

    @Override
    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            if (key != null && bitmap != null) {
                mMemoryCache.put(key, bitmap);
            }
        }
    }

    @Override
    public Bitmap getBitmapFromMemCache(String key) {
        return key == null ? null : mMemoryCache.get(key);
    }


    @Override
    public boolean cancleImageViewWork(ImageView imageView) {
        final BitmapTask task = getWorkTask(imageView);
        if (task != null) {
            return task.cancel(true);
        }

        return false;
    }

    public void release() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            mMemoryCache.trimToSize(0);
        }
    }


    private static boolean cancelWork(String data, ImageView imageView) {
        final BitmapTask task = getWorkTask(imageView);

        if (task != null) {
            final String res = task.mResource;
            if (res == null || !res.equals(data)) {
                task.cancel(true);
            } else {
                return false;
            }
        }
        return true;
    }

    private static BitmapTask getWorkTask(ImageView imageView) {
        Drawable drawable = imageView.getDrawable();
        if (drawable instanceof AsyncDrawable) {
            return (BitmapTask) ((AsyncDrawable) drawable).getAsyncTask();
        }
        return null;
    }

    private static class AsyncDrawable extends ThumbnailDrawable {
        private WeakReference<AsyncTask> mReferences = null;


        public AsyncDrawable(Resources res, Bitmap bitmap, AsyncTask task) {
            super(res, bitmap);
            this.mReferences = new WeakReference<AsyncTask>(task);
        }

        public AsyncTask getAsyncTask() {
            return mReferences.get();
        }

    }

    protected abstract Bitmap getBitmapFormUrl(String url);

    private class BitmapTask extends AsyncTask<String, Void, Bitmap> {
        private WeakReference<ImageView> mReference;
        private String mResource = null;

        private BitmapTask(ImageView imageView) {
            mReference = new WeakReference<ImageView>(imageView);
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            mResource = params[0];
            Bitmap bitmap = null;
            if ((bitmap = getBitmapFromMemCache(params[0])) == null) {
                bitmap = getBitmapFormUrl(params[0]);
            }
            addBitmapToMemoryCache(params[0], bitmap);
            return bitmap;
        }



/*        private Bitmap getVideoThumbnail(String videoPath, int width, int height,
                                         int kind) {
            Bitmap bitmap = null;
            bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);

            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
            return bitmap;
        }*/


        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (isCancelled())
                return;

            final ImageView imageView = mReference.get();
            if (imageView != null) {
//                AsyncDrawable drawable = (AsyncDrawable) imageView.getDrawable();
                final BitmapTask task = getWorkTask(imageView);
                if (task == this) {
                    imageView.setImageBitmap(bitmap);
                }
            }

        }
    }
}